package ex01.pyrmont;


import com.sky.JULLog.MyLogger;

import java.io.InputStream;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 解析 http 请求, 包括请求头和 请求地址
 */
public class Request {


    private static Logger log = MyLogger.getLogger(Request.class);
    private InputStream input;
    private String uri;

    protected Request(InputStream input) {
        this.input = input;
    }

    protected void parse() {


        // Read a set of characters from the socket
        StringBuffer request = new StringBuffer(2048);
        int i;
        byte[] buffer = new byte[2048];
        try {
            i = input.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            i = -1;
        }
        for (int j = 0; j < i; j++) {
            request.append((char) buffer[j]);
        }
        log.info("浏览器请求信息 \n" + request.toString());
        uri = parseUri(request.toString());
    }

    private String parseUri(String requestString) {
        int index1, index2;
        index1 = requestString.indexOf(' ');
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
            if (index2 > index1) {
                return requestString.substring(index1 + 1, index2);
            }
        }
        return null;
    }

    protected String getUri() {
        if (uri != null) {
            uri = uri.replaceAll("//", "\\");  //如果是Windows
        }
        return uri;
    }

}
